package inge_soft.gestoriusNuevo.persistence.DAO.implementation;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import inge_soft.gestoriusNuevo.persistence.DAO.abstraction.IEventoDAO;
import inge_soft.gestoriusNuevo.persistence.entity.implementation.Actividad;
import inge_soft.gestoriusNuevo.persistence.entity.implementation.Evento;
import inge_soft.gestoriusNuevo.persistence.entity.implementation.Institucion;

@Repository("eventoDAO")
public class EventoDAO implements IEventoDAO {

	@PersistenceContext
	private EntityManager entityManager;
	
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Evento> obtenerTodosEventos(Institucion institucion) throws DataAccessException {
		Query query = entityManager.createQuery("SELECT e FROM Evento e WHERE e.institucion = :institucion");
		query.setParameter("institucion", institucion);
		return query.getResultList();
	}

	@Transactional(propagation = Propagation.MANDATORY)
	public void crearEvento(Institucion institucion, Evento evento) throws DataAccessException {
		evento.setInstitucion(institucion);
		evento.setListaActividades(new ArrayList<Actividad>());
		entityManager.persist(evento);
	}

	@Transactional(propagation = Propagation.MANDATORY)
	public void modificarEvento(Evento evento) throws DataAccessException {
		entityManager.merge(evento);
	}

	public Date primerFecha() {
			Query query = entityManager.createQuery("SELECT MIN(fechaInicio) FROM Evento");
		return (Date) query.getSingleResult();
	}

	@Transactional(propagation = Propagation.MANDATORY)
	public Evento obtenerEvento(Long idEvento){
		Query query = entityManager.createQuery("SELECT e FROM Evento e WHERE e.id = :idEvento");
		query.setParameter("idEvento", idEvento);
		return (Evento)query.getSingleResult();
	}

	
}
